package com.sys.SysWaterQuality.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.sys.SysAlerts.domain.SysAlerts;
import com.sys.SysAlerts.mapper.SysAlertsMapper;
import com.sys.SysAquaticSpecies.domain.SysAquaticSpecies;
import com.sys.SysAquaticSpecies.mapper.SysAquaticSpeciesMapper;
import com.sys.SysTanks.domain.SysTanks;
import com.sys.SysTanks.mapper.SysTanksMapper;
import com.sys.SysWaterQuality.domain.SysWaterQuality;
import com.sys.SysWaterQuality.mapper.SysWaterQualityMapper;
import com.sys.common.annotation.Anonymous;
import com.sys.common.core.controller.BaseController;
import com.sys.common.core.domain.AjaxResult;
import com.sys.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;
/**
 * 水质实时数据数据集成调用请求
 *
 * @author ruoyi
 * @date 2025-09-03
 */
@Anonymous
@RestController
@RequestMapping(value = "/webHook")
public class WebHookController extends BaseController {

    //实时水质Mapper
    @Autowired
    private SysWaterQualityMapper sysWaterQualityMapper;
    //养殖桶Mapper
    @Autowired
    private SysTanksMapper sysTanksMapper;
    //养殖桶生物信息Mapper
    @Autowired
    private SysAquaticSpeciesMapper sysAquaticSpeciesMapper;

    //警告记录Mapper
    @Autowired
    private SysAlertsMapper sysAlertsMapper;

    /**
     * 接收水位信息
     *   // 1. 参数校验
     *     // 2. 解析tankId（含异常捕获）
     *     // 3. 查询养殖桶配置（含空值检查）
     *     // 4. 获取温度阈值
     *     // 5. 温度范围检查并触发告警
     *     // 6. 保存水质记录
     *     // 7. 统一返回结果
     *     现在我的思路是:
     *     1.先拿到传递过来的数据，让对数据进行处理，
     *     2.获取到这个养殖桶所养生物的标准数据，和获取到的数据通过自定义规则进行对比，
     *     3.对处理过后的数据进行入库操作，
     */
    @Anonymous
    @PostMapping(value = "/notify")
    public AjaxResult notify(@RequestBody Map<Object , Object> body) {
        // 提取所需字段
        String id = (String) body.get("id");
        String clientid = (String) body.get("clientid");
        String payloadStr = (String) body.get("payload");
        System.out.println("接收到数据："+payloadStr+"  id:"+id+"  clientid:"+clientid);
        JSONObject payloadJson = JSON.parseObject(payloadStr);
        // 提取 water_level 对应的数值-->水深
        BigDecimal waterLevel = payloadJson.getBigDecimal("temperature");
        System.out.println("温度："+waterLevel);
        //从clientid提取 tank_id
        String[] parts = clientid.split("_");
        String lastPart = parts[parts.length - 1];
        int tankId = Integer.parseInt(lastPart);
        //获取水温标准值
        //根据养殖桶id拿到生物信息id
        SysTanks sysTanks = sysTanksMapper.selectSysTanksById((long) tankId);
        Long speciesId = sysTanks.getSpeciesId();
//        System.out.println("获取养殖桶信息："+sysTanks);
        //根据生物信息id拿到水温标准值
        SysAquaticSpecies sysAquaticSpecies = sysAquaticSpeciesMapper.selectSysAquaticSpeciesById(speciesId);
        //获取最低水温
        BigDecimal minTemp = sysAquaticSpecies.getMinTemp();
        //获取最高水温
        BigDecimal maxTemp = sysAquaticSpecies.getMaxTemp();
        //如果水温小于最低水温
        if (waterLevel.compareTo(minTemp)<0) {
            SysAlerts record = new SysAlerts();
            record.setTankId(tankId);
            record.setAlertType("水温");
            record.setSeverity("中度");
            record.setMessage("水温低于标准");
            record.setStatus("1");
            record.setAlertTime(new Date());
            record.setResolvedBy(0);
            record.setCreateTime(new Date());
            record.setUpdateTime(new Date());
            sysAlertsMapper.insertSysAlerts(record);
        }
        //如果水温大于最高水温
        if (waterLevel.compareTo(maxTemp)>0) {
            SysAlerts record = new SysAlerts();
            record.setTankId(tankId);
            record.setAlertType("水温");
            record.setSeverity("重度");
            record.setMessage("水温高于标准");
            record.setStatus("1");
            record.setAlertTime(new Date());
            record.setResolvedBy(0);
            record.setCreateTime(new Date());
            record.setUpdateTime(new Date());
            sysAlertsMapper.insertSysAlerts(record);
        }
//        // 创建实体对象并设置值
        SysWaterQuality record = new SysWaterQuality();
        record.setId(id);
        record.setTankId(tankId);
        record.setTemperature(waterLevel); // water_level值存入temperature字段
        record.setUpdateTime(new Date());
        record.setRecordTime(new Date()); // 记录时间为当前时间
        record.setCreateTime(new Date()); // 创建时间为当前时间
//        System.out.println( record);
//        // 插入数据库
        int result = sysWaterQualityMapper.insertSysWaterQuality(record);
//        System.out.println("插入结果："+result);
        return toAjax(result);
    }
}